<template>
  <div class="root-house-mng">
    <div class="root-house-mng-main">
      <Popover title="筛选" trigger="click" placement="rightTop">
        <template #content>
          <BasicForm
            class="x-village-tabs"
            submitOnReset
            @register="registerForm"
            @submit="handleSearchInfoChange"
            v-bind="getFormProps"
          >
            <template #[replaceFormSlotKey(item)]="data" v-for="item in getFormSlotKeys">
              <slot :name="item" v-bind="data || {}"></slot>
            </template>
          </BasicForm>
        </template>
        <Button class="x-houseMng-search" type="primary" shape="circle">
          <SearchOutlined />
        </Button>
      </Popover>

      <div :id="mapViewId" style="height: calc(100vh - 140px)"></div>
    </div>
  </div>
</template>

<script lang="ts">
  //import maplibregl from '/@/utils/lib/mapre/maplibre-gl.js';
  //import '/@/utils/lib/mapre/maplibre-gl.css';
  import { createImgPreview, ImagePreview } from '/@/components/Preview/index';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBasicColumns, tablePopupSchema } from './tableData';
  import { PageWrapper } from '/@/components/Page';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Tabs, Space, Divider, PageHeader, Tag, Collapse, Button, Popover } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import {
    defineComponent,
    onMounted,
    reactive,
    ref,
    ComputedRef,
    computed,
    defineAsyncComponent,
    nextTick,
  } from 'vue';
  import { houseListApi, houseApi } from '/@/api/demo/table';
  import * as tableDataPopup from '/@/views/map/tableDataPopup';
  import { useGlobSetting } from '/@/hooks/setting';
  const globSetting = useGlobSetting();
  import { getSearchFormSchema } from '/@/views/house/tableData';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  const { info, success, warning, error } = createMessage;
  import { FormProps, FormSchema } from '/@/components/Table';
  import AuditModal from './AuditModal.vue';
  import { useModal } from '/@/components/Modal';
  import type { UserInfo } from '/#/store';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { useDrawer } from '/@/components/Drawer';

  const imgList: string[] = [];
  export default defineComponent({
    name: 'HouMng',
    components: {
      ImagePreview,
      BasicTable,
      BasicForm,
      AuditModal,
      TableAction,
      PageWrapper,
      Tabs,
      Divider,
      PageHeader,
      Space,
      SearchOutlined,
      Popover,
      Collapse,
      Tag,
      TabPane: Tabs.TabPane,
      Button,
    },
    props: {
      msg: String,
      mapViewId: {
        type: String,
        default: 'map',
      },
      showMapOnly: {
        type: Boolean,
        default: false,
      },
      showMapPopupButtons: {
        type: Boolean,
        default: true,
      },
    },
    setup(props, { attrs, emit, slots, expose }) {
      const activeKeyRef = ref('map');
      const activePickKeyRef = ref('fire');
      const activeMapPickKeyRef = ref('map');
      const searchVisible = ref(false);
      const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;

      const mapC = ref(maplibregl.Map);
      const pickedHouse = ref({});
      const pickedHouseId = ref('');
      const houseFirePlaceRef = ref();
      const housePolicePlaceRef = ref();

      const userStore = useUserStore();

      function calcModes(user: UserInfo) {
        if (user) {
          if ('Admin' == user.role) {
            return ['fire', 'police', 'housing'];
          } else {
            if ('FireControl' == user.userGroup) {
              return ['fire'];
            } else if ('Police' == user.userGroup) {
              return ['police'];
            } else if ('Housing' == user.userGroup) {
              return ['housing'];
            }
          }
        }

        return [];
      }

      const underMode = calcModes(userStore.getUserInfo);

      const tk = userStore.getToken;
      let protocol = window.document.location.protocol;
      let host = window.document.location.host;
      let localhostPath = protocol + '//' + host;

      //图斑权限过滤
      const { jurisdictionCodes } = userStore.getUserInfo;
      const buzlinebaseFilter: Array<any> = [];
      if (jurisdictionCodes) {
        buzlinebaseFilter.push('any');
        for (let i = 0; i < jurisdictionCodes.length; i++) {
          const code = jurisdictionCodes[i].regionCode;
          const subcode = code.replace(/[0]*$/, '');
          console.log(subcode);
          buzlinebaseFilter.push(['in', subcode, ['get', 'village']]);
        }
      }
      let filterFinal = buzlinebaseFilter.length > 0 ? buzlinebaseFilter : ['any', true];
      const userGroup = userStore.getUserGroup;

      //对于公安用户，数据只能显示107的
      if (userGroup == 'Police') {
        filterFinal = ['all', filterFinal, ['==', ['get', 'check107'], 1]];
      }

      const mapstyle = reactive<maplibregl.Style>({
        version: 8,
        sources: {
          OSM: {
            type: 'raster',
            tiles: [
              'http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=82917dfddef988b400ff306a56c1c7de',
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
          tianditu: {
            type: 'raster',
            tiles: [
              'http://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk==82917dfddef988b400ff306a56c1c7de',
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
          buzBase: {
            type: 'vector',
            scheme: 'xyz',
            tiles: [
              `${uriBase}/houses/base/static/vector/tiles?x={x}&y={y}&z={z}&access_token=${tk}`,
            ],
            minzoom: 11,
            maxzoom: 18,
          },
          buz: {
            type: 'vector',
            scheme: 'xyz',
            tiles: [`${uriBase}/houses/dynamic/vector/tiles?x={x}&y={y}&z={z}&access_token=${tk}`],
            minzoom: 11,
            maxzoom: 18,
          },
          highLight: {
            type: 'geojson',
            data: {
              type: 'FeatureCollection',
              features: [],
            },
          },
          baseMap: {
            type: 'geojson',
            data: `${localhostPath}/xzq/jiedao.geojson`,
          },
        },
        layers: [
          {
            id: 'OSM',
            type: 'raster',
            source: 'OSM',
          },
          {
            id: 'baseMap',
            type: 'line',
            source: 'baseMap',
            paint: {
              'line-color': 'yellow',
              'line-width': 2,
              'line-dasharray': [1, 1],
            },
            maxzoom: 13,
          },
          {
            id: 'baseMap-anno',
            type: 'symbol',
            source: 'baseMap',
            minzoom: 11,
            maxzoom: 15,
            layout: {
              'text-field': '{NAME}',
              'text-font': ['DIN Offc Pro Medium,Arial Unicode MS Regular'],
              'text-size': 18,
            },
            paint: {
              'text-color': 'rgb(255,255,255)',
              'text-halo-width': 1,
              'text-halo-color': 'rgb(0,0,0)',
            },
          },
          {
            id: 'buzlinebase',
            'source-layer': 'fflayer',
            type: 'fill',
            source: 'buzBase',
            minzoom: 1,
            maxzoom: 22,
            paint: {
              'fill-outline-color': 'rgb(255,0,0)',
              'fill-opacity': 0.3,
            },
            filter: filterFinal,
          },
          {
            id: 'buzlinebase2',
            'source-layer': 'fflayer',
            type: 'line',
            source: 'buzBase',
            minzoom: 1,
            maxzoom: 22,
            paint: {
              'line-color': 'rgb(255,0,0)',
              'line-width': 2,
            },
            filter: filterFinal,
          },

          {
            id: 'buzline',
            'source-layer': 'ffpolygon',
            type: 'line',
            source: 'buz',
            minzoom: 14,
            maxzoom: 22,
            paint: {
              'line-color': {
                type: 'categorical',
                property: 'pcztfire', // 必写
                stops: [
                  [0, 'red'],
                  [1, 'green'],
                  [2, 'yellow'],
                ],
              },
              'line-width': 2,
            },
          },
          {
            id: 'buz',
            'source-layer': 'ffpolygon',
            type: 'fill',
            source: 'buz',
            minzoom: 14,
            maxzoom: 22,
            paint: {
              'fill-color': 'black',
              'fill-opacity': 0.3,
            },
          },

          {
            id: 'buz-anno',
            'source-layer': 'ffpolygon',
            type: 'symbol',
            source: 'buz',
            minzoom: 17,
            maxzoom: 22,
            layout: {
              'text-field': '{address}',
              'text-font': ['DIN Offc Pro Medium,Arial Unicode MS Regular'],
              'text-size': 15,
              'text-max-width': 30,
            },
            paint: {
              'text-color': 'rgb(255,255,255)',
              'text-halo-width': 1,
              'text-halo-color': 'rgb(0,0,0)',
            },
          },
          {
            id: 'highLight',
            type: 'fill',
            source: 'highLight',
            paint: {
              'fill-opacity': 0.6,
              'fill-color': 'blue',
            },
          },
        ],
        sprite: `${localhostPath}/maplib/sprites/sprite`,
        glyphs: `${localhostPath}/maplib/font/{fontstack}/{range}.pbf`,
      });
      const mapopC: maplibregl.Popup[] = [];
      function clickPopUpOk(_) {
        if (mapopC.length > 0) {
          mapopC[0].remove();
        }
      }

      const [register5, { openDrawer: openDrawer5, setDrawerProps }] = useDrawer();

      function clickPopupButtonOk(obj) {
        pickedHouse.value = obj;
        pickedHouseId.value = obj.id;

        emit('onPopupButtonOkClick', obj);
      }

      function createPopUp(features) {
        return tableDataPopup.createPopUp(
          features,
          tablePopupSchema(),
          clickPopUpOk,
          houseApi,
          clickPopupButtonOk,
          {
            visibleButtons: props.showMapPopupButtons,
          },
        );
      }

      function popupInfo(e) {
        if (e.features && e.features.length > 0) {
          const geojsonData: any = {
            type: 'FeatureCollection',
            features: e.features,
          };
          const map = mapC.value;
          var mySource: maplibregl.GeoJSONSource = map.getSource(
            'highLight',
          ) as maplibregl.GeoJSONSource;
          mySource.setData(geojsonData);

          //创建内容
          createPopUp(e).then((popupTemp) => {
            let currentPopup = new maplibregl.Popup();
            currentPopup.addClassName('click-map-popup');
            currentPopup.setLngLat(e.lngLat).setDOMContent(popupTemp).addTo(map);

            mapopC.length = 0;
            mapopC.push(currentPopup);
          });
        }
      }
      onMounted(() => {
        const map = new maplibregl.Map({
          container: props.mapViewId,
          style: mapstyle,
          center: [116.5, 40.05],
          zoom: 9,
          maxZoom: 20,
        });
        mapC.value = map;
        map.on('click', 'buzlinebase', function (e) {
          //const zoom = map.getZoom();
          //const value = Math.pow(2, 22 - zoom);
          //const { lng, lat } = e.lngLat;
          //const center = wgs84ToMercator(lng, lat);
          //const min = [center.x - value, center.y - value];
          //const max = [center.x + value, center.y + value];
          //const min = webMercator2LngLat(center.x - value, center.y - value);
          //const max = webMercator2LngLat(center.x + value, center.y + value);
          // 查询WMS要素属性
          console.log(e);
          popupInfo(e);
        });

        function webMercator2LngLat(x: any, y: any) {
          var lng = (x / 20037508.34) * 180;
          var lat = (y / 20037508.34) * 180;
          lat = (180 / Math.PI) * (2 * Math.atan(Math.exp((lat * Math.PI) / 180)) - Math.PI / 2);
          return [lng, lat];
        }

        function latLng2WebMercator2(lng, lat) {
          var x = (lng * 20037508.34) / 180;
          var y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180);
          y = (y * 20037508.34) / 180;
          return [x, y];
        }

        // 经纬度转墨卡托
        function wgs84ToMercator(lng: any, lat: any) {
          lng = parseFloat(lng);
          lat = parseFloat(lat);
          var d = Math.PI / 180;
          const max = 90;
          lat = Math.max(Math.min(max, lat), -max);
          const sin = Math.sin(lat * d);
          var x = 6378137 * lng * d;
          var y = (6378137 * Math.log((1 + sin) / (1 - sin))) / 2;
          return {
            x,
            y,
          };
        }
      });

      const [registerModal, callbackUseModal] = useModal();

      function cloneSearchSchema(serSchema: FormSchema[]) {
        var serSchemaClone: FormSchema[] = [];
        serSchema.forEach((ele) => {
          const a: FormSchema = Object.assign({}, ele);
          a.colProps = { span: 12, flex: 1 };
          serSchemaClone.push(a);
        });

        return serSchemaClone;
      }

      var serSchema = getSearchFormSchema(underMode);

      const [registerTable, { reload }] = useTable({
        api: houseListApi,
        columns: getBasicColumns(),
        pagination: { pageSize: 10 },
        formConfig: {
          schemas: cloneSearchSchema(serSchema),
        },
        useSearchForm: true,
        bordered: true,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      function handleReloadCurrent() {
        reload();
      }

      function handleReload() {
        reload({
          page: 1,
        });
      }

      function handleSuccess() {
        reload();
      }

      function onBack2Map() {
        pickedHouseId.value = '';
        pickedHouse.value = '';
      }

      function handlePreview(record: Recordable) {
        const onImgLoad = ({ index, url, dom }) => {
          console.log(`第${index + 1}张图片已加载，URL为：${url}`, dom);
        };
        imgList.length = 0;
        if (record.photos) {
          let photos = record.photos.split(',');
          photos.forEach((ele) => {
            if (ele) imgList.push(`${globSetting.apiBaseUrl}/api/v1/images/${ele}`);
          });
        }
        // 可以使用createImgPreview返回的 PreviewActions 来控制预览逻辑，实现类似幻灯片、自动旋转之类的骚操作
        createImgPreview({ imageList: imgList, defaultWidth: 700, rememberState: true, onImgLoad });
      }

      function handleStatus(record: Recordable) {
        callbackUseModal.openModal(true, {
          record,
          isUpdate: true,
        });
      }
      function handleLocMap(record: Recordable) {
        activeKeyRef.value = 'map';
        let lng = record.lng;
        let lat = record.lat;
        let coordinates: maplibregl.LngLatLike = [lng, lat];
        const mapL = mapC.value;
        mapL.flyTo({
          center: coordinates, // 中心点
          zoom: 14, // 缩放比例
        });
        clickPopUpOk({});
        houseApi(record).then((resp: any) => {
          const e: any = {
            lngLat: coordinates,
            features: [
              {
                properties: record,
                geometry: JSON.parse(resp.geometry),
              },
            ],
          };

          popupInfo(e);
        });
      }
      function locMap(houseId) {
        mapC.value.resize();
        houseApi({ id: houseId })
          .then((record) => {
            let lng = (record.boundingBox.xMin + record.boundingBox.xMax) / 2;
            let lat = (record.boundingBox.yMin + record.boundingBox.yMax) / 2;
            let coordinates: maplibregl.LngLatLike = [lng, lat];
            const mapL = mapC.value;
            mapL.flyTo({
              center: coordinates, // 中心点
              zoom: 14, // 缩放比例
            });
            clickPopUpOk({});
            const e: any = {
              lngLat: coordinates,
              features: [
                {
                  properties: record,
                  geometry: JSON.parse(record.geometry),
                },
              ],
            };

            popupInfo(e);
          })
          .catch((err) => {
            error(err.message || '获取房屋信息失败');
          });
      }

      const getFormProps = computed((): Partial<FormProps> => {
        return {
          showAdvancedButton: false,
          compact: true,
          actionColOptions: { span: 6 },
          schemas: cloneSearchSchema(serSchema),
        };
      });

      function handleSearchInfoChange(info: Recordable) {}
      const [registerForm, formActions] = useForm();
      const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
        const keys = Object.keys(slots);
        return keys
          .map((item) => (item.startsWith('form-') ? item : null))
          .filter((item) => !!item) as string[];
      });
      function replaceFormSlotKey(key: string) {
        if (!key) return '';
        return key?.replace?.(/form\-/, '') ?? '';
      }
      const showDrawer = () => {
        searchVisible.value = true;
      };
      return {
        imgList,
        activeKeyRef,
        activePickKeyRef,
        activeMapPickKeyRef,
        registerForm,
        getFormSlotKeys,
        replaceFormSlotKey,
        getFormProps,
        handleSearchInfoChange,
        registerTable,
        handlePreview,
        handleLocMap,
        handleStatus,
        handleReloadCurrent,
        handleReload,
        locMap,
        registerModal,
        handleSuccess,
        searchVisible,
        showDrawer,
        register5,
        pickedHouse,
        pickedHouseId,
        houseFirePlaceRef,
        housePolicePlaceRef,
        onBack2Map,
      };
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }

  .root-house-mng-main {
    margin: 6px;
  }

  .x-village-tabs {
    //z-index: 100;
    //position: absolute;
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    //background-color: rgba(34, 34, 34, 0.6);
    :deep(.ant-form) {
      margin-top: 6px;
    }

    // :deep(.ant-form-item-label) > label {
    //   color: white;
    // }
  }
</style>
